package org.example.ding.controller;

import org.example.ding.entity.User;
import org.example.ding.service.CustomUserDetailsService;
import org.example.ding.service.NutritionService;
import org.example.ding.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * 营养控制器
 */
@Controller
@RequestMapping("/nutrition")
public class NutritionController {

    @Autowired
    private NutritionService nutritionService;
    
    @Autowired
    private UserService userService;

    /**
     * 获取今日营养进度API
     */
    @GetMapping("/api/progress")
    @ResponseBody
    public ResponseEntity<?> getTodayProgress(
            @AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal) {

        if (principal == null) {
            return ResponseEntity.status(401).build();
        }

        try {
            User user = userService.findByUsername(principal.getUsername()).orElse(null);
            if (user == null) {
                return ResponseEntity.status(404).build();
            }

            var nutrition = nutritionService.getTodayNutrition(user);
            return ResponseEntity.ok(nutrition);

        } catch (Exception e) {
            System.err.println("获取营养进度失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 营养仪表盘页面
     */
    @GetMapping("/dashboard")
    public String dashboard(
            @AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal,
            @org.springframework.web.bind.annotation.RequestParam(required = false)
            @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE)
            java.time.LocalDate date,
            org.springframework.ui.Model model) {

        if (principal == null) {
            return "redirect:/login";
        }

        try {
            User user = userService.findByUsername(principal.getUsername()).orElse(null);
            if (user == null) {
                return "redirect:/login";
            }

            java.time.LocalDate targetDate = (date != null) ? date : java.time.LocalDate.now();
            boolean isToday = targetDate.equals(java.time.LocalDate.now());

            model.addAttribute("user", principal);
            model.addAttribute("targetDate", targetDate);
            model.addAttribute("isToday", isToday);

            // 使用简化页面，避免缺少复杂模型数据导致模板错误
            return "nutrition/dashboard-simple";
        } catch (Exception e) {
            System.err.println("营养仪表盘加载失败: " + e.getMessage());
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 今日点餐记录（简化列表，用于营养仪表盘）
     */
    @GetMapping("/api/today-orders")
    @ResponseBody
    public ResponseEntity<?> getTodayOrders(
            @AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal) {
        if (principal == null) {
            return ResponseEntity.status(401).build();
        }
        try {
            User user = userService.findByUsername(principal.getUsername()).orElse(null);
            if (user == null) {
                return ResponseEntity.status(404).build();
            }
            java.time.LocalDate today = java.time.LocalDate.now();
            var orders = nutritionService.getTodayOrders(principal.getId());
            // 返回精���JSON，避免懒加载循环
            java.util.List<java.util.Map<String, Object>> result = new java.util.ArrayList<>();
            for (org.example.ding.entity.OrderRecord o : orders) {
                java.util.Map<String, Object> m = new java.util.HashMap<>();
                m.put("id", o.getId());
                m.put("mealType", o.getMealType().name());
                m.put("dishName", o.getDish().getName());
                m.put("portionSize", o.getPortionSize());
                m.put("actualCalories", o.getActualCalories());
                m.put("actualProtein", o.getActualProtein());
                m.put("actualCarbs", o.getActualCarbs());
                m.put("actualFat", o.getActualFat());
                result.add(m);
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            System.err.println("获取今日点餐记录失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }
}
